package com.example.swimmingpool.util;

import com.example.swimmingpool.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
@Slf4j
public class MinioUtil {

    private final MinioClient client;

    private final MinioConfig config;


    @Autowired
    public MinioUtil(MinioConfig minioConfig) {
        this.config = minioConfig;
        this.client = MinioClient.builder().endpoint(minioConfig.getEndpoint())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();

    }

    public void createBucket(String bucketName) {
        var args = BucketExistsArgs.builder().bucket(bucketName).build();
        try {
            if (!client.bucketExists(args)) {
                var build = MakeBucketArgs.builder().bucket(bucketName).build();
                client.makeBucket(build);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void download(String objectName, String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        var args = DownloadObjectArgs.builder()
                .bucket(config.getBucket())
                .object(objectName)
                .filename(fileName)
                .build();
        client.downloadObject(args);
    }

    public InputStream get(String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        var args = GetObjectArgs.builder()
                .bucket(config.getBucket())
                .object(objectName).build();
        return client.getObject(args);
    }

    public void put(String objectName, InputStream in, String contentType) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        var args = PutObjectArgs.builder()
                .bucket(config.getBucket())
                .object(objectName)
                .stream(in, -1, 10485760)
                .contentType(contentType)
                .build();
        client.putObject(args).etag();
    }


}
